package main;

import config.DatabassAccessObject;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class FootBathManagementSystem extends JFrame {
    private DatabassAccessObject dao;

    public FootBathManagementSystem() {
        try {
            dao = new DatabassAccessObject();
            startupInterface();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }



    private void showFootBathProjectsManagementDialog() {
        JFrame jFrame = new JFrame("足浴项目管理");
        jFrame.setLayout(new BorderLayout());

        // 添加表格用于显示足浴项目
        DefaultTableModel tableModel = new DefaultTableModel();
        JTable footBathProjectsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(footBathProjectsTable);
        jFrame.add(scrollPane, BorderLayout.CENTER);

        // 初始化表格列
        tableModel.addColumn("项目ID");
        tableModel.addColumn("项目名称");
        tableModel.addColumn("项目价格");

        // 加载足浴项目数据
        loadFootBathProjects(tableModel);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("添加");
        JButton deleteButton = new JButton("删除");
        JButton updateButton = new JButton("修改");
        JButton backButton = new JButton("退出");

        buttonPanel.add(addButton);
        buttonPanel.add(deleteButton);
        buttonPanel.add(updateButton);
        buttonPanel.add(backButton);
        jFrame.add(buttonPanel, BorderLayout.SOUTH);

        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行添加足浴项目的逻辑
                showAddFootBathProjectDialog(tableModel);
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行删除足浴项目的逻辑
                int selectedRow = footBathProjectsTable.getSelectedRow();
                if (selectedRow != -1) {
                    int projectId = (int) tableModel.getValueAt(selectedRow, 0);
                    deleteFootBathProject(projectId, tableModel);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要删除的足浴项目");
                }
            }
        });

        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行更新足浴项目的逻辑
                int selectedRow = footBathProjectsTable.getSelectedRow();
                if (selectedRow != -1) {
                    int projectId = (int) tableModel.getValueAt(selectedRow, 0);
                    showUpdateFootBathProjectDialog(projectId, tableModel);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要更新的足浴项目");
                }
            }
        });


        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose(); // 关闭足浴项目管理界面
                startupInterface();
            }
        });

        jFrame.setSize(400, 300);
        jFrame.setLocationRelativeTo(this);
        jFrame.setVisible(true);
    }



    private void startupInterface() {
        JFrame  jFrame = new JFrame ("欢迎来到足浴管理系统");
        jFrame.setLayout(new BorderLayout());

        // 添加文本框面板
        JPanel textFieldPanel = new JPanel();
        JTextField nameField = new JTextField(20);
        JPasswordField passwordField = new JPasswordField(20);

        textFieldPanel.add(new JLabel("用户名:"));
        textFieldPanel.add(nameField);
        textFieldPanel.add(new JLabel("密码: "));
        textFieldPanel.add(passwordField);

        jFrame.add(textFieldPanel, BorderLayout.CENTER);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);

        jFrame.add(buttonPanel, BorderLayout.SOUTH);

        loginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 获取用户名和密码
                String name = nameField.getText();
                char[] passwordChars = passwordField.getPassword();
                String password = new String(passwordChars);
                try {
                    String searchQuery = "SELECT * FROM user WHERE name = ? AND password = ?";
                    ResultSet resultSet = dao.query(searchQuery, name, password);
                    if (resultSet.next()) {
                        int userId = resultSet.getInt("id");
                        if ("admin".equals(name)) {
                            // 关闭对话框
                            jFrame.dispose();
                            showFootBathProjectsManagementDialog();
                        }else {
                            // 关闭对话框
                            jFrame.dispose();
                            //用户界面
                            userInterface(userId);
                        }
                    } else {
                        JOptionPane.showMessageDialog(null, "用户名或密码错误", "错误", JOptionPane.ERROR_MESSAGE);
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    JOptionPane.showMessageDialog(null, "验证用户时发生错误");
                }


            }
        });

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                showMemberRegistrationDialog();
            }
        });

        jFrame.setSize(300, 250);
        jFrame.setLocationRelativeTo(this);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jFrame.setVisible(true);
    }

    private void userInterface(int userId){
        JFrame jFrame = new JFrame("足浴管理系统");
        jFrame.setLayout(new BorderLayout());
        // 添加大字标题
        JLabel titleLabel = new JLabel("欢迎使用足浴管理系统");
        titleLabel.setFont(new Font("SansSerif", Font.BOLD, 20)); // 设置字体样式
        titleLabel.setHorizontalAlignment(JLabel.CENTER); // 居中对齐
        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        JButton subscribeButton = new JButton("项目预约");
        JButton orderButton = new JButton("订单查询");
        JButton backButton = new JButton("退出");

        buttonPanel.add(subscribeButton);
        buttonPanel.add(orderButton);
        buttonPanel.add(backButton);
        jFrame.add(buttonPanel, BorderLayout.SOUTH);
// 将标题和按钮面板添加到对话框的NORTH和SOUTH位置
        jFrame.add(titleLabel, BorderLayout.NORTH);
        subscribeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose();
                projectReservation(userId);
            }
        });

        orderButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose();
                orderInquiry(userId);
            }
        });
        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose(); // 关闭足浴项目管理界面
                startupInterface();
            }
        });

        jFrame.setSize(360, 110);
        jFrame.setLocationRelativeTo(this);
        jFrame.setVisible(true);
    }

    private void trackTheOrder(int userId,DefaultTableModel tableModel) {
        try {
            String query = "SELECT f2.*,f1.order_time FROM foot_bath_order f1  LEFT JOIN foot_bath_project f2 ON f1.project_id = f2.project_id WHERE f1.user_id = ?";
            ResultSet resultSet = dao.query(query,userId);

            while (resultSet.next()) {
                int projectId = resultSet.getInt("project_id");
                if (projectId == 0){
                    continue;
                }
                String projectName = resultSet.getString("project_name");
                double projectPrice = resultSet.getDouble("price");
                Date orderTime = resultSet.getTimestamp("order_time");

                Date currentDate = new Date();

                int comparisonResult = orderTime.compareTo(currentDate);
                String type = "";
                if (comparisonResult < 0) {
                    type = "已使用";
                } else if (comparisonResult > 0) {
                    type = "未使用";
                } else {
                    type = "进行中";
                }

                Object[] rowData = {projectId, projectName, projectPrice,orderTime,type};
                tableModel.addRow(rowData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void orderInquiry(int userId){
        JFrame jFrame = new JFrame("订单查询");
        jFrame.setLayout(new BorderLayout());

        // 添加表格用于显示足浴项目
        DefaultTableModel tableModel = new DefaultTableModel();
        JTable footBathProjectsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(footBathProjectsTable);
        jFrame.add(scrollPane, BorderLayout.CENTER);

        // 初始化表格列
        tableModel.addColumn("项目ID");
        tableModel.addColumn("项目名称");
        tableModel.addColumn("项目价格");
        tableModel.addColumn("预约时间");
        tableModel.addColumn("使用状态");

        // 加载足浴项目数据
        trackTheOrder(userId,tableModel);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        JButton cancelButton = new JButton("取消订单");
        JButton backButton = new JButton("退出");

        buttonPanel.add(cancelButton);
        buttonPanel.add(backButton);
        jFrame.add(buttonPanel, BorderLayout.SOUTH);

        cancelButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行更新足浴项目的逻辑
                int selectedRow = footBathProjectsTable.getSelectedRow();
                if (selectedRow != -1) {
                    int projectId = (int) tableModel.getValueAt(selectedRow, 0);
                    Date orderTime = (Date) tableModel.getValueAt(selectedRow,3);
                    Date currentDate = new Date();

                    int comparisonResult = orderTime.compareTo(currentDate);
                    if (comparisonResult > 0) {
                        try {
                            String deleteQuery = "Delete from foot_bath_order where user_id = ? and project_id = ?";
                            dao.modify(deleteQuery, userId, projectId);
                            tableModel.setRowCount(0); // 清空表格数据
                            trackTheOrder(userId,tableModel); // 重新加载
                        } catch (Exception e1) {
                            e1.printStackTrace();
                            JOptionPane.showMessageDialog(null, "取消足浴项目时发生错误");

                        }
                        JOptionPane.showMessageDialog(null, "取消成功");
                    }else {
                        JOptionPane.showMessageDialog(null, "不可取消", "错误", JOptionPane.ERROR_MESSAGE);
                    }

                } else {
                    JOptionPane.showMessageDialog(null, "请选择要取消的足浴项目");
                }
            }
        });

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose(); // 关闭足浴项目管理界面
                userInterface(userId);
            }
        });

        jFrame.setSize(530, 300);
        jFrame.setLocationRelativeTo(this);
        jFrame.setVisible(true);
    }

    private void projectReservation(int userId){
        JFrame jFrame = new JFrame("项目预约");
        jFrame.setLayout(new BorderLayout());

        // 添加表格用于显示足浴项目
        DefaultTableModel tableModel = new DefaultTableModel();
        JTable footBathProjectsTable = new JTable(tableModel);
        JScrollPane scrollPane = new JScrollPane(footBathProjectsTable);
        jFrame.add(scrollPane, BorderLayout.CENTER);

        // 初始化表格列
        tableModel.addColumn("项目ID");
        tableModel.addColumn("项目名称");
        tableModel.addColumn("项目价格");

        // 加载足浴项目数据
        loadFootBathProjects(tableModel);

        // 添加按钮面板
        JPanel buttonPanel = new JPanel();
        JButton payButton = new JButton("购买");
        JButton backButton = new JButton("退出");

        buttonPanel.add(payButton);
        buttonPanel.add(backButton);
        jFrame.add(buttonPanel, BorderLayout.SOUTH);

        payButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 执行更新足浴项目的逻辑
                int selectedRow = footBathProjectsTable.getSelectedRow();
                if (selectedRow != -1) {
                    int projectId = (int) tableModel.getValueAt(selectedRow, 0);
                    appointmentTime(userId,projectId, tableModel);
                } else {
                    JOptionPane.showMessageDialog(null, "请选择要购买的足浴项目");
                }
            }
        });

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                jFrame.dispose(); // 关闭足浴项目管理界面
                userInterface(userId);
            }
        });

        jFrame.setSize(400, 300);
        jFrame.setLocationRelativeTo(this);
        jFrame.setVisible(true);
    }



    private static JSpinner createTimeSpinner() {
        SpinnerDateModel model = new SpinnerDateModel();
        JSpinner spinner = new JSpinner(model);

        // 设置时间格式，包含年月日时分秒
        JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "yyyy-MM-dd HH:mm:ss");
        spinner.setEditor(editor);

        return spinner;
    }

    private void showMemberRegistrationDialog() {
        JTextField nameField = new JTextField();
        JTextField passwordField = new JTextField();

        Object[] message = {
                "用户名:", nameField,
                "密码:", passwordField
        };

        int option = JOptionPane.showConfirmDialog(null, message, "会员注册", JOptionPane.OK_CANCEL_OPTION);

        if (option == JOptionPane.OK_OPTION) {
            String name = nameField.getText();
            String phoneNumber = passwordField.getText();

            if (name.isEmpty() || phoneNumber.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            try {
                String searchQuery = "SELECT * FROM user WHERE name = ?";
                ResultSet resultSet = dao.query(searchQuery, name);
                if (resultSet.next()) {
                    JOptionPane.showMessageDialog(null, "用户名已存在", "错误", JOptionPane.ERROR_MESSAGE);
                    return;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

            saveMemberToDatabase(name, phoneNumber);

            JOptionPane.showMessageDialog(this, "会员注册成功", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void saveMemberToDatabase(String name, String password) {
        try {
            String insertQuery = "INSERT INTO user (password, name) VALUES ( ?, ?)";
            dao.insert(insertQuery, password, name);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "保存会员信息时发生错误");
        }
    }

    private void showAddFootBathProjectDialog(DefaultTableModel tableModel) {
        String projectName = JOptionPane.showInputDialog(null, "请输入足浴项目名称");
        if (projectName != null && !projectName.isEmpty()) {
            String priceStr = JOptionPane.showInputDialog(null, "请输入足浴项目价格");
            if (priceStr != null && !priceStr.isEmpty()) {
                try {
                    double projectPrice = Double.parseDouble(priceStr);
                    addFootBathProject(projectName, projectPrice, tableModel);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "请输入有效的数字作为价格");
                }
            } else {
                JOptionPane.showMessageDialog(null, "请输入足浴项目价格");
            }
        } else {
            JOptionPane.showMessageDialog(null, "请输入足浴项目名称");
        }
    }

    private void showUpdateFootBathProjectDialog(int projectId, DefaultTableModel tableModel) {
        String projectName = JOptionPane.showInputDialog(null, "请输入新的足浴项目名称");
        if (projectName != null && !projectName.isEmpty()) {
            String priceStr = JOptionPane.showInputDialog(null, "请输入新的足浴项目价格");
            if (priceStr != null && !priceStr.isEmpty()) {
                try {
                    double projectPrice = Double.parseDouble(priceStr);
                    updateFootBathProject(projectId, projectName, projectPrice, tableModel);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "请输入有效的数字作为价格");
                }
            } else {
                JOptionPane.showMessageDialog(null, "请输入新的足浴项目价格");
            }
        } else {
            JOptionPane.showMessageDialog(null, "请输入新的足浴项目名称");
        }
    }

    private void appointmentTime(int userId,int projectId, DefaultTableModel tableModel) {
        JSpinner timeSpinner = createTimeSpinner(); // 创建时间选择器
        int option = JOptionPane.showOptionDialog(null, timeSpinner, "请输入预约时间", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null);

        // 判断用户是否点击了 "确定"
        if (option == JOptionPane.OK_OPTION) {
            Date appointmentTime = (Date) timeSpinner.getValue();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
            String orderTime = dateFormat.format(appointmentTime);
            try {
                String insertQuery = "INSERT INTO foot_bath_order (user_id, project_id, order_time) VALUES (?, ?, ?)";
                dao.insert(insertQuery, userId, projectId,orderTime);
            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, "购买足浴项目时发生错误");
            }
            JOptionPane.showMessageDialog(null, "预约成功");
        }
    }



    private void loadFootBathProjects(DefaultTableModel tableModel) {
        try {
            String query = "SELECT * FROM foot_bath_project";
            ResultSet resultSet = dao.query(query);

            while (resultSet.next()) {
                int projectId = resultSet.getInt("project_id");
                String projectName = resultSet.getString("project_name");
                double projectPrice = resultSet.getDouble("price");

                Object[] rowData = {projectId, projectName, projectPrice};
                tableModel.addRow(rowData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void addFootBathProject(String projectName, double projectPrice, DefaultTableModel tableModel) {
        try {
            String insertQuery = "INSERT INTO foot_bath_project (project_name, price) VALUES (?, ?)";
            dao.insert(insertQuery, projectName, projectPrice);
            tableModel.setRowCount(0); // 清空表格数据
            loadFootBathProjects(tableModel); // 重新加载
            } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "添加足浴项目时发生错误");
        }
    }

    private void deleteFootBathProject(int projectId, DefaultTableModel tableModel) {
        try {
            String deleteQuery = "DELETE FROM foot_bath_project WHERE project_id = ?";
            dao.modify(deleteQuery, projectId);
            tableModel.setRowCount(0); // 清空表格数据
            loadFootBathProjects(tableModel); // 重新加载
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "删除足浴项目时发生错误");
        }
    }

    private void updateFootBathProject(int projectId, String projectName, double projectPrice, DefaultTableModel tableModel) {
        try {
            String updateQuery = "UPDATE foot_bath_project SET project_name = ?, price = ? WHERE project_id = ?";
            dao.modify(updateQuery, projectName, projectPrice, projectId);
            tableModel.setRowCount(0); // 清空表格数据
            loadFootBathProjects(tableModel); // 重新加载
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "更新足浴项目时发生错误");
        }
    }

    public static void main(String[] args) {
        new FootBathManagementSystem();
    }
}